
<template>
    <div class="ingr-related-herb-comp" ref="ingrRelatHerb">
         <TitleBox>
            <template #titlecont>
                <span v-lang="{lang: controlSto.language, lgid: -70}">Related herb</span>
            </template>
        </TitleBox>

        <div class="condition-box">
            <div class="condition-left">
                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -44}">List sort</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-radio-group v-model="condObj.sort" @change="toSearch">
                                <div class="cond-radio-wrap">
                                    <el-radio class="cond-radio-item" value="Asc"><span v-lang="{lang: controlSto.language, lgid: -49}"></span></el-radio>
                                    <el-radio class="cond-radio-item" value="Desc"><span v-lang="{lang: controlSto.language, lgid: -50}"></span></el-radio>
                                </div>
                            </el-radio-group>
                        </div>
                    </template>
                </SearchDrop>
                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -48}">Flavor</span>
                        <!-- <el-popover placement="top-start">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.FlavorAll"
                                @change="allChooseFlavor"
                            >
                            <span @click.stop="condObj.FlavorAll = !condObj.FlavorAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <template #reference>
                                <span v-lang="{lang: controlSto.language, lgid: -48}">Flavor</span>
                            </template>
                        </el-popover> -->
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.FlavorAll"
                                @change="allChooseFlavor"
                            >
                            <span @click.stop="condObj.FlavorAll = !condObj.FlavorAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <el-checkbox-group v-model="condObj.flavorList"  @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in dataObj.flavorList" :key="'flavor_' + item.id" :value="item.flavorCode" :label="item.flavorName"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>

                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -47}">Property</span>
                        <!-- <el-popover placement="top-start">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.PropertyAll"
                                @change="allChooseProperty"
                            >
                            <span @click.stop="condObj.PropertyAll = !condObj.PropertyAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <template #reference>
                                <span v-lang="{lang: controlSto.language, lgid: -47}">Property</span>
                            </template>
                        </el-popover> -->
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.PropertyAll"
                                @change="allChooseProperty"
                            >
                            <span @click.stop="condObj.PropertyAll = !condObj.PropertyAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <el-checkbox-group v-model="condObj.propList"  @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in dataObj.proptyList" :key="'prop_' + item.id" :value="item.propertyCode" :label="item.propertyName"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>


                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -85}">Meridians</span>
                        <!-- <el-popover placement="top-start">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.MeridiansAll"
                                @change="allChooseMeridians"
                            >
                            <span @click.stop="condObj.MeridiansAll = !condObj.MeridiansAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <template #reference>
                                <span v-lang="{lang: controlSto.language, lgid: -85}">Meridians</span>
                            </template>
                        </el-popover> -->
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.MeridiansAll"
                                @change="allChooseMeridians"
                            >
                            <span @click.stop="condObj.MeridiansAll = !condObj.MeridiansAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <el-checkbox-group v-model="condObj.meridiansList"  @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in dataObj.meridiansList" :key="'specy_' + item.id" :value="item.meridiansCode" :label="item.meridiansName"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>
            </div>
            <div class="condition-right">
                <div class="ipt-cont">
                    <el-input clearable="true" class="ipt-search" v-model="condObj.searchword" autofocus :placeholder="searchPlace" />
                </div>
                <SearchBtn class="search-item" @click.stop="toSearch"/>

                <TableFilter class="search-item" :column="dataObj.columnList" :filterKey="condObj.filterKey" @onChg="chgTableCol"/>
            
                <SearchLoad type='ingredientRelateHerb' :uiCode="condObj.uiCode" :para="{
                    'content': condObj.searchword,
                    'herbFlavorCode': condObj.flavorList.join(','),
                    'herbPropertyCode': condObj.propList.join(','),
                    'herbMeridiansCode': condObj.meridiansList.join(','),
                    'ingrId': detailId,
                    'langCode': controlSto.language == 1 ? 'ENG' : 'CHN',
                    'sortType': condObj.sort,
                    'uiTypeCode': condObj.uiCode
                }"/>
            </div>
        </div>


        <div class="cont-box">
            <uiTable
                :config="dataObj.tableConfig"
                :columnConfig="dataObj.columnConfig" 
                :data="dataObj.dataList"
                :loading="isLoading"
                :key="dataObj.searchTablevt">
                <template #[condObj.idField]="{ row }">
                    <div class="jump-box" @click.stop="toClkItem(row)"><span>{{row[condObj.idField]}}</span></div>
                </template>
                <template #[condObj.nameField]="{ row }">
                    <el-tooltip placement="top" :content="row[condObj.nameField]" v-if="row[condObj.nameField] && row[condObj.nameField].length > 20">
                        <div class="jump-box table-jump-name" @click.stop="toClkItem(row)"><span>{{row[condObj.nameField]}}</span></div>
                    </el-tooltip>
                    <div v-else class="jump-box" @click.stop="toClkItem(row)"><span>{{row[condObj.nameField]}}</span></div>
                </template>
            </uiTable>
            <div class="page-box" v-if=" condObj.total > 10">
                <uiPagination
                    :total="condObj.total" :pageSize="condObj.pageSize" :pageIndex="condObj.pageIndex"
                    @onSizeChange="chgSize" @onCurrentChange="chgCurrnt"/>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, reactive, toRefs, computed, onBeforeMount, watch } from 'vue';
    import { useIntersectionObserver } from '@vueuse/core';
    import TitleBox from '@/components/TitleBox.vue'
    import SearchBtn from '@/components/SearchBtn.vue'
    import TableFilter from '@/components/TableFilter.vue'
    import SearchLoad from '@/components/SearchLoad.vue'
    import uiTable from '@/components/ui-table.vue'
    import uiPagination from '@/components/ui-pagination.vue'
    import SearchDrop from '@/components/SearchDrop.vue'
    import { useRouter } from 'vue-router'

    import { langTxt, getFilterThArr, getFilterLangArr } from '@/utils/util'
    import { getTableThList, getIngredientRelatedHerb, getHerbFlavorList, getHerbPropertyList, getHerbmeridiansList } from '@/service/tcm'
    // import { flavorList, propertyList, merdiansList } from '@/utils/database'

    import { controlStore } from '@/stores/control'
    import { debounce } from 'lodash'
    
    const emitter = defineEmits(['toCalc']);
    const props = defineProps({
        detailId: {
            type: [Number, String],
            default: ''
        }
    });
    const { detailId } = toRefs(props);
    const router = useRouter();
    const ingrRelatHerb = ref(null);
    
    let searchDebounce = null;

    const controlSto = controlStore();
    const isLoading = ref(true);

    const condObj = reactive({
        idField: '100716826576556928',
        nameField: '100716826576556929',
		searchword: '',
		filterKey: 'ingr8',
        uiCode: 'herb',
        word: '',
        total: 0,
        pageSize: 10,
        pageIndex: 1,
        flavorList: [],
		propList: [],
		meridiansList: [],
        sort: 'Asc',
        FlavorAll: true,
		MeridiansAll: true,
		PropertyAll: true
	});

	const dataObj = reactive({
		searchTablevt: 1,
		columnList: [],
		tableConfig: {
			// size: 'small',
			'tooltip-effect': 'dark',
			'highlight-current-row': true,
			stripe: true,
			'header-cell-style': { background: '#BC9F77', color: '#FFF' },
		},
		columnConfig: [],
		dataList: [],
        flavorList: [],
		proptyList: [],
		meridiansList: [],
	});

    const searchPlace = computed(() => {
		return langTxt(controlSto.language, '-15');
	});

    onBeforeMount(()=> {
        // toGetHerbFlavorList();
		// toGetHerbPropertyList();
		// toGetHerbMeridiansList();
        // initDebounce();
		// getTableTh();
        // toGetData();
        const {stop} = useIntersectionObserver(
            ingrRelatHerb,
            ([{ isIntersecting }], observerElement) => {
                if (isIntersecting) {
                    // 停止监听，如果你只想知道一次可视性变化
                    initDebounce();
                    getTableTh();
                    // toGetData();
                    getAllData();
                    //阻止再次请求
                    stop()
                }
            },
            {
                threshold: 0, // 当交叉框达到视窗的这部分时触发
            }
        );
    });

    const initDebounce = () => {
        searchDebounce = debounce((e) => {
            getDataList();
        }, 400);
    };
   
    const getTableTh = () => {
        let params = {
            uiCode: condObj.uiCode,
            langCode: 'ENG,CHN'
        };
        
        getTableThList(params).then((res) => {
            if (res.success) {
                let arr = res.data || [];
                let thArr = getFilterThArr(arr, dataObj.filterKey);
        		let langArr = getFilterLangArr(thArr);
        		controlSto.setLangList(langArr);
        		dataObj.columnList = thArr;
            }
        }).catch(() => {});

        // let thArr = getFilterThArr(arr, condObj.filterKey);
        // let langArr = getFilterLangArr(thArr);
        // controlSto.setLangList(langArr);
        // dataObj.columnList = thArr;
    };

    const chgTableCol = (e) => {
		dataObj.columnConfig = e || [];
		dataObj.searchTablevt = new Date().valueOf();
        emitter('toCalc');
    };

    
    const toGetData = () => {
        searchDebounce && searchDebounce();
    };
    const getAllData = () => {
        const param = {langCode: controlSto.language == 1 ? 'ENG' : 'CHN'}
        Promise.all([getHerbFlavorList(param), getHerbPropertyList(param), getHerbmeridiansList(param)]).then(res => {
            if (res[0].success && res[0].data) {
                condObj.flavorList = [];
                dataObj.flavorList = res[0].data || [];
                res[0].data.forEach(e => {
                    condObj.flavorList.push(e.flavorCode)
                })
            }
            if (res[1].success && res[1].data) {
                condObj.propList = [];
                dataObj.proptyList = res[1].data || [];
                res[1].data.forEach(e => {
                    condObj.propList.push(e.propertyCode)
                })
            }
            if (res[2].success && res[2].data) {
                condObj.meridiansList = [];
                dataObj.meridiansList = res[2].data || [];
                res[2].data.forEach(e => {
                    condObj.meridiansList.push(e.meridiansCode)
                })
            }
            getDataList();
        }).catch(() => {})
    }
    const getDataList = () => {
        let params = {
            langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
            ingrId: detailId.value,
            content: condObj.word,
            uiTypeCode: condObj.uiCode,
			pageNo: condObj.pageIndex || 10,
			pageSize: condObj.pageSize || 1,
            sortType: condObj.sort,
            herbFlavorCode: condObj.flavorList.join(','),
            herbPropertyCode: condObj.propList.join(','),
            herbMeridiansCode: condObj.meridiansList.join(',')
        };
        isLoading.value = true;
        getIngredientRelatedHerb(params).then((res) => {
            isLoading.value = false;
            if (res.success && res.data && res.data.records) {
                dataObj.dataList = res.data.records || [];
                condObj.total = res.data.totalCount || 0;
            }
        }).catch(() => {
            isLoading.value = false;
        });

        emitter('toCalc');
    };

    const toClkItem = (row) => {
        router.push({ name: 'herbdetail' , query: {id: row[condObj.idField]} });
    }
        
    const chgSize = (e) => {
        condObj.pageSize = e || 10;
        toGetData();
    };
    const chgCurrnt = (e) => {
        condObj.pageIndex = e || 1;
        toGetData();
    };
    const toSearch = () => {
        condObj.word = condObj.searchword;
        condObj.pageIndex = 1;
        toGetData();
    };

    const allChooseMeridians = () => {
		if(condObj.meridiansList.length == dataObj.meridiansList.length) {
			condObj.meridiansList = []
		} else {
			condObj.meridiansList = [];
			dataObj.meridiansList.forEach(e => {
				condObj.meridiansList.push(e.meridiansCode)
			})
		}
	}
	const allChooseProperty = () => {
		if(condObj.propList.length == dataObj.proptyList.length) {
			condObj.propList = []
		} else {
			condObj.propList = [];
			dataObj.proptyList.forEach(e => {
				condObj.propList.push(e.propertyCode)
			})
		}
	}
	const allChooseFlavor = () => {
		if(condObj.flavorList.length == dataObj.flavorList.length) {
			condObj.flavorList = [];
		} else {
			condObj.flavorList = [];
			dataObj.flavorList.forEach(e => {
				condObj.flavorList.push(e.flavorCode)
			})
		}
	}
    
    watch(() => controlSto.language, (n, v) => {
        if(n != v && v) {
            // toGetHerbFlavorList();
            // toGetHerbPropertyList();
            // toGetHerbMeridiansList();
            // toGetData();
            getAllData();
        }
    }, { immediate: true });
    watch(() => [condObj.flavorList, condObj.propList, condObj.meridiansList], (n, v) => {
		if(n != v) toSearch()
		if(n[0].length == dataObj.flavorList.length) condObj.FlavorAll = true;
		else condObj.FlavorAll = false;

		if(n[1].length == dataObj.proptyList.length) condObj.PropertyAll = true;
		else condObj.PropertyAll = false;

		if(n[2].length == dataObj.meridiansList.length) condObj.MeridiansAll = true;
		else condObj.MeridiansAll = false;
	}, { immediate: true })

</script>


<style lang="scss" scoped>
    .ingr-related-herb-comp {
        margin-bottom: 32px;
        .condition-box {
            display: flex;
            padding: 24px 0;
            justify-content: space-between;
            .condition-left {
                .cond-item {
                    margin-right: 16px;
                }
            }
            .condition-right {
                .ipt-cont {
                    display: inline-block;
                    padding-right: 16px;
                    .ipt-search {
                        // width: 300px;
                    }
                }
                .search-item {
                    margin-right: 16px;
                }
            }
        }
        .cont-box {

        }
    }
</style>
